import { cloneDeep } from "lodash-es";
import { ref } from "vue";
import type { Ref, UnwrapRef } from "vue";

type AsyncFn<T> = (...args: any[]) => Promise<T>
/**
 * @description 带接口请求的数据,可以立即请求
 */
export function useStateWithFetch<T, P extends AsyncFn<T> = AsyncFn<T>> (data: T, fn: P, options: {immediate: boolean} = { immediate: true }): [Ref<UnwrapRef<T>>, (...args: Parameters<P>) => void] {
  const refData = ref(data);
  function update (...args: any[]) {
    fn(...args).then(res => {
      refData.value = res as UnwrapRef<T>;
    });
  }
  if (options.immediate) {
    update();
  }

  return [refData, update];
}
/**
 * @description 可以将数据重置为传入的值
 */
export function useStateWithReset<T> (data: T): [Ref<UnwrapRef<T>>, (resetFns?: ((...args: any[]) => any)[]) => void, (data?: T) => void] {
  let initialData = cloneDeep(data);
  const refData = ref(data);
  function reset (resetFns?: ((...args: any[]) => any)[]) {
    refData.value = cloneDeep(initialData) as UnwrapRef<T>;
    resetFns?.forEach(item => {
      item?.();
    });
  }
  function updateData (data?: T) {
    if (data) {
      initialData = cloneDeep(data);
    } else {
      initialData = cloneDeep(refData.value) as T;
    }
  }

  return [refData, reset, updateData];
}
